package com.java.zhuiyun.api.memberShip_records.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.java.zhuiyun.api.alipay.controller.AliPay;
import com.java.zhuiyun.api.front_desk_user.entity.FrontDeskUser;
import com.java.zhuiyun.api.front_desk_user.mapper.FrontDeskUserMapper;
import com.java.zhuiyun.api.home.mapper.HomeMapper;
import com.java.zhuiyun.api.home.model.ModelOrder;
import com.java.zhuiyun.api.home.model.SalesVolumeYear;
import com.java.zhuiyun.api.memberShip_records.entity.UserMemberShip;
import com.java.zhuiyun.api.memberShip_records.mapper.MemberShipMapper;
import com.java.zhuiyun.api.memberShip_records.model.EchartsMemberModels;
import com.java.zhuiyun.api.memberShip_records.model.MemberShipModel;
import com.java.zhuiyun.api.memberShip_records.service.MemberShipService;
import com.java.zhuiyun.api.member_manager.entity.MemberType;
import com.java.zhuiyun.api.member_manager.mapper.MemberTypeMapper;
import com.java.zhuiyun.common.response.CommonResult;
import com.java.zhuiyun.util.pageUtil.MybatisPageHelper;
import com.java.zhuiyun.util.pageUtil.PageRequest;
import com.java.zhuiyun.util.pageUtil.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * @ClassName MemberShipServiceImpl
 * @Description TODO 会员记录业务逻辑实现
 * @Author WX
 * @Date 2023/8/18 8:52
 **/
@Service
public class MemberShipServiceImpl implements MemberShipService {

    @Autowired
    private MemberShipMapper memberShipMapper;
    @Autowired
    private MemberTypeMapper memberTypeMapper;
    @Autowired
    private FrontDeskUserMapper frontDeskUserMapper;
    @Autowired
    private HomeMapper homeMapper;

    /*
     * @Author WX
     * @Description 生成订单
     * @Date 2023/8/18 9:01
     * @Return
     * @param UserMemberShip
     */
    @Override
    public String generateOrder(UserMemberShip userMemberShip) {
        // 获取对象中的会员类型id
        Integer id = userMemberShip.getMemberId();
        // 查询该类型id下的数据
        MemberType memberType = memberTypeMapper.fingById(id);
        // 获取对象中的用户id
        Integer codeId = userMemberShip.getUserId();
        List<UserMemberShip> us = memberShipMapper.findByUserId(codeId);
        // 设置支付金额
        userMemberShip.setPayPrice(memberType.getPrice());
        // 设置创建时间/开通时间
        userMemberShip.setCreateTime(new Date());
        // 设置修改时间
        userMemberShip.setUpdateTime(new Date());
        // 生成到期时间
        Date createTime = new Date();
        LocalDateTime createDateTime = createTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        LocalDateTime expireDateTime = createDateTime.plus(memberType.getDuration(), ChronoUnit.MONTHS);
        Date expireTime = Date.from(expireDateTime.atZone(ZoneId.systemDefault()).toInstant());
        userMemberShip.setExpiryTime(expireTime);
        // 生成一个自己的20位订单编码
        // 设置一个时间格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMddHHmm");
        // 将当前时间转换为string类型
        String currentTime = dateFormat.format(new Date());
        String userMemberShipId = fillLeftWithRandomChars(String.valueOf(userMemberShip.getUserId()), 3);
        String memberShipId = fillLeftWithRandomChars(String.valueOf(userMemberShip.getMemberId()), 3);
        // 生成订单号
        String memberNumber  = currentTime + userMemberShipId + memberShipId;
        userMemberShip.setMemberNumber(memberNumber );

        int i = memberShipMapper.generateOrder(userMemberShip);
        return memberNumber;
    }

    /*
     * @Author WX
     * @Description 查询个人会员购买记录
     * @Date 2023/8/18 13:57
     * @Return
     * @param id
     */
    @Override
    public List<MemberShipModel> personInfoQuery(Integer id) {
        List<MemberShipModel> memberShipModelList = memberShipMapper.personInfoQuery(id);
        if (memberShipModelList.size()>0){
            return memberShipModelList;
        }else {
            return null;
        }
    }

    /*
     * @Author WX
     * @Description 订单支付
     * @Date 2023/8/18 13:57
     * @Return
     * @param id
     */
    @Override
    public int updateById(AliPay aliPay) {
        // 获取对象中的会员类型id
        Integer id = aliPay.getMemberId();
        Integer userId = aliPay.getUserId();
        // 查询该类型id下的数据
        MemberType memberType = memberTypeMapper.fingById(id);
        FrontDeskUser frontDeskUser = frontDeskUserMapper.findTimeByUserId(userId);

        LocalDateTime currentDateTime = LocalDateTime.now(); // 获取当前时间

        if (frontDeskUser.getFrontDeskMemberTime() != null) {
            Date frontDeskMemberDate = frontDeskUser.getFrontDeskMemberTime();
            Instant instant = frontDeskMemberDate.toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime frontDeskMemberDateTime = LocalDateTime.ofInstant(instant, zoneId);

            if (frontDeskMemberDateTime.isAfter(currentDateTime)) {
                // frontDeskMemberTime 大于当前时间
                LocalDateTime expireDateTime = frontDeskMemberDateTime.plus(memberType.getDuration(), ChronoUnit.MONTHS);
                Date expiryTime = Date.from(expireDateTime.atZone(ZoneId.systemDefault()).toInstant());
                aliPay.setExpiryTime(expiryTime);
            } else {
                // frontDeskMemberTime 小于等于当前时间
                LocalDateTime expireDateTime = currentDateTime.plus(memberType.getDuration(), ChronoUnit.MONTHS);
                Date expiryTime = Date.from(expireDateTime.atZone(ZoneId.systemDefault()).toInstant());
                aliPay.setExpiryTime(expiryTime);
            }
        }else {
            LocalDateTime expireDateTime = currentDateTime.plus(memberType.getDuration(), ChronoUnit.MONTHS);
            Date expiryTime = Date.from(expireDateTime.atZone(ZoneId.systemDefault()).toInstant());
            aliPay.setExpiryTime(expiryTime);
        }
        return memberShipMapper.updateById(aliPay);
    }

    /*
     * @Author WX
     * @Description 查询所有会员记录
     * @Date 2023/8/28 11:23
     * @Return
     * @param null
     */
    @Override
    public CommonResult selectMemberShip(PageRequest pageRequest) {
        MybatisPageHelper.startPage(pageRequest);
        List<MemberShipModel> backCourseModels = memberShipMapper.selectMemberShip();
        PageResult pageResult = MybatisPageHelper.getPageResult(backCourseModels);
        return CommonResult.ok(pageResult);
    }

    /*
     * @Author WX
     * @Description 查询各种会员本月购买记录
     * @Date 2023/8/28 14:20
     * @Return
     * @param null
     */
    @Override
    public List<EchartsMemberModels> getMembers() {
        List<MemberType> memberTypes = memberTypeMapper.getMemberList();
        List<Integer> memberIds = new ArrayList<>();

        // 1. 存储 memberId 和 memberName 的对应关系
        Map<Integer, String> memberIdToNameMap = new HashMap<>();
        for (MemberType memberType : memberTypes) {
            memberIdToNameMap.put(memberType.getId(), memberType.getMemberName());
        }

        // 2. 统计不同 memberId 对应的数据数量
        Map<String, Integer> memberDataCountMap = new HashMap<>();
        for (MemberType memberType : memberTypes) {
            int memberId = memberType.getId();
            List<MemberShipModel> memberDataList = memberShipMapper.getMembers(Collections.singletonList(memberId));
            int memberDataCount = memberDataList.size();
            memberDataCountMap.put(memberIdToNameMap.get(memberId), memberDataCount);
        }

        // 3. 构建 ECharts 所需的 X 轴和 Y 轴数据
        List<String> xAxis = new ArrayList<>();
        List<Integer> yAxis = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : memberDataCountMap.entrySet()) {
            xAxis.add(entry.getKey());
            yAxis.add(entry.getValue());
        }

        // 4. 返回包含 X 轴和 Y 轴数据的自定义对象或者直接返回 Map
        // 这里使用自定义对象的例子，你可以根据实际情况进行调整
        List<EchartsMemberModels> eChartsData = new ArrayList<>();
        for (int i = 0; i < xAxis.size(); i++) {
            EchartsMemberModels dataPoint = new EchartsMemberModels();
            dataPoint.setName(xAxis.get(i));
            dataPoint.setValue(yAxis.get(i));
            eChartsData.add(dataPoint);
        }
        return eChartsData;
    }

    @Override
    public CommonResult getOrdersMembersmonth(String selectedYear) {
        Map<String, Object> resultMap = new HashMap<>();
        SalesVolumeYear salesVolumeYear =homeMapper.getAllqq(selectedYear);
        SalesVolumeYear salesVolumeYear1 =homeMapper.getAllmember(selectedYear);
        if(salesVolumeYear==null){
            resultMap.put("getgetqq", 0);
        }else{
            resultMap.put("getgetqq", salesVolumeYear.getPrice());
        }

        if(salesVolumeYear1 ==null){
            resultMap.put("getmember", 0);
        }else {
            resultMap.put("getmember", salesVolumeYear1.getPrices());
        }

        return CommonResult.ok(resultMap);
    }

    /*
     * @Author WX
     * @Description 当年会员月销量
     * @Date 2023/9/7 10:17
     * @Return
     * @param null
     */
    @Override
    public CommonResult getMemberMonth(String selectedYear) {
        List<String> qwe = new ArrayList<>();
        List<Integer> qqq = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            ModelOrder modelOrder = memberShipMapper.getMemberMonth(String.valueOf(i),selectedYear);
            Integer name = modelOrder.getMonth();
            Integer eng = modelOrder.getPrice();
            if (modelOrder.getMonth() == null){
                qwe.add(i+"月");
                qqq.add(eng);
            }else {
                qwe.add(name+"月");
                qqq.add(eng);
            }
        }
        return CommonResult.ok(CollUtil.newArrayList(qwe, qqq));
    }

    /*@Override
    public CommonResult getOrdersMembersmonth() {
        return null;
    }*/


    /*
        * @Author WX
        * @Description 自动补足用户编号和会员编号
        * @Date 2023/8/18 10:39
        * @Return
        * @param null
        */
    public static String fillLeftWithRandomChars(String str, int length) {
        // 假如获取的长度大于定义的长度就以定义长度随机截取获取的数据
        if (str.length() > length) {
            int startIndex = new SecureRandom().nextInt(str.length() - length + 1);
            return str.substring(startIndex, startIndex + length);
        } else {
            StringBuilder sb = new StringBuilder(str);
            SecureRandom random = new SecureRandom();
            byte[] bytes = new byte[length - sb.length()];
            random.nextBytes(bytes);
            for (byte b : bytes) {
                sb.insert(0, (char) ('A' + Math.abs(b % 26)));
            }
            return sb.toString();
        }
    }

}
